//
//  ENWebViewController.m
//  EverydayNews
//
//  Created by 李沛池 on 2017/7/18.
//  Copyright © 2017年 Godlike. All rights reserved.
//

#import "ENWebViewController.h"
#import "ENInterface.h"
#import "SharesModel.h"
#import "ENSharesCell.h"
#import "LPCTableView.h"
#import "ENSharesTableHeaderView.h"

@interface ENWebViewController ()<
UITableViewDelegate,
UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UIWebView *webView;
@property (weak, nonatomic) IBOutlet LPCTableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *viewShangZ;
@property (weak, nonatomic) IBOutlet UILabel *labelSZNowPrice;
@property (weak, nonatomic) IBOutlet UILabel *labelSZDiffPrice;
@property (weak, nonatomic) IBOutlet UILabel *labelSZDiffRate;
@property (weak, nonatomic) IBOutlet UIImageView *iViewArrowShangZ;

@property (weak, nonatomic) IBOutlet UIView *viewShenZ;
@property (weak, nonatomic) IBOutlet UILabel *labelShenZNowPrice;
@property (weak, nonatomic) IBOutlet UILabel *labelShenZDiffPrice;
@property (weak, nonatomic) IBOutlet UILabel *labelShenZDiffRate;
@property (weak, nonatomic) IBOutlet UIImageView *iViewArrowShenZ;

@end

@implementation ENWebViewController
{
    NSInteger _currentPage;
    NSMutableArray *_arrayShares;
    BOOL _currentSortUP;//YES UP NO Down
    LPCMBProgressHUD *_hud;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    //    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self updateSharesUI];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    //    self.tabBarController.tabBar.hidden = NO;
    self.tabBarController.navigationItem.rightBarButtonItems = nil;
}

- (void)initData
{
    _currentPage = 1;
    [self requestSharesList];
}

- (void)initUI
{
    [self initTableViewHeader];
    
    for (UIView *view in @[_viewShangZ,_viewShenZ]) {
        view.layer.cornerRadius = 4;
        view.layer.shadowColor = COLOR_FFFFFF(0xb5b5b5).CGColor;
        view.layer.shadowOffset = CGSizeMake(0, 2);
        view.layer.shadowOpacity = 0.5;
        view.layer.shadowRadius = 4;
    }
}

- (void)initTableViewHeader
{
//    _tableView.tableHeaderView = XIBFromMainBundle(@"ENSharesTableHeaderView");
}

- (void)updateSharesUI
{
    [self updateNavBar];
}

- (void)updateNavBar
{
    self.tabBarController.navigationItem.title = @"股市行情";
    
    UIButton * btnRefresh = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnRefresh setImage:[UIImage imageNamed:@"util_refresh"] forState:UIControlStateNormal];
    [btnRefresh addTarget:self action:@selector(refreshShares) forControlEvents:UIControlEventTouchUpInside];
    [btnRefresh sizeToFit];
    UIBarButtonItem * refreshBarButton = [[UIBarButtonItem alloc] initWithCustomView:btnRefresh];
    
    UIBarButtonItem *searchBarBtnItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"util_search_white"] style:UIBarButtonItemStylePlain target:self action:@selector(pushToSearchShares)];
    [searchBarBtnItem setImageInsets:UIEdgeInsetsMake(2, -5, 0, 5)];
    
    self.tabBarController.navigationItem.rightBarButtonItems = @[refreshBarButton,searchBarBtnItem];
}

- (void)updateHeadView:(NSArray *)arrayIndexList
{
    NSDictionary *dicShangZ = arrayIndexList[0];
    _labelSZNowPrice.text = dicShangZ[@"nowPrice"];
    
    UIColor *shangZColor = COLOR_RED_Shares;
    if ([dicShangZ[@"diff_rate"] floatValue] < 0) {
        shangZColor = COLOR_GREEN_Shares;
        _labelSZDiffPrice.text = [NSString stringWithFormat:@"%@",dicShangZ[@"diff_money"]];
        _labelSZDiffRate.text = [NSString stringWithFormat:@"%@%%",dicShangZ[@"diff_rate"]];
        _iViewArrowShangZ.image = ImageNamed(@"util_arrow_down_green");
    }else {
        _labelSZDiffPrice.text = [NSString stringWithFormat:@"+%@",dicShangZ[@"diff_money"]];
        _labelSZDiffRate.text = [NSString stringWithFormat:@"+%@%%",dicShangZ[@"diff_rate"]];
        _iViewArrowShangZ.image = ImageNamed(@"util_arrow_up_red");
    }
    _labelSZNowPrice.textColor = shangZColor;
    _labelSZDiffPrice.textColor = shangZColor;
    _labelSZDiffRate.textColor = shangZColor;
    
    NSDictionary *dicShenZ = arrayIndexList[1];
    _labelShenZNowPrice.text = dicShenZ[@"nowPrice"];
    
    UIColor *shenZColor = COLOR_RED_Shares;
    if ([dicShenZ[@"diff_rate"] floatValue] < 0) {
        shenZColor = COLOR_GREEN_Shares;
        _labelShenZDiffPrice.text = [NSString stringWithFormat:@"%@",dicShenZ[@"diff_money"]];
        _labelShenZDiffRate.text = [NSString stringWithFormat:@"%@%%",dicShenZ[@"diff_rate"]];
        _iViewArrowShenZ.image = ImageNamed(@"util_arrow_down_green");
    }else {
        _labelShenZDiffPrice.text = [NSString stringWithFormat:@"+%@",dicShenZ[@"diff_money"]];
        _labelShenZDiffRate.text = [NSString stringWithFormat:@"+%@%%",dicShenZ[@"diff_rate"]];
        _iViewArrowShenZ.image = ImageNamed(@"util_arrow_up_red");
    }
    _labelShenZNowPrice.textColor = shenZColor;
    _labelShenZDiffPrice.textColor = shenZColor;
    _labelShenZDiffRate.textColor = shenZColor;
}


#pragma mark - Custom
- (void)sortShares:(BOOL)isUP
{
    _currentSortUP = isUP;
    
    [_arrayShares sortUsingComparator:^NSComparisonResult(SharesModel *  _Nonnull obj1, SharesModel *  _Nonnull obj2) {
        if ([obj1.diff_rate floatValue] > [obj2.diff_rate floatValue]) {
            return isUP==YES?NSOrderedDescending:NSOrderedAscending;
        }else if ([obj1.diff_rate floatValue] < [obj2.diff_rate floatValue]) {
            return isUP==YES?NSOrderedAscending:NSOrderedDescending;
        }else {
            
        }
        return NSOrderedSame;
    }];
}


#pragma mark - Action

- (void)backHome
{
//    self.tabBarController.selectedIndex = 0;
}

- (void)refreshShares
{
    [self requestSharesList];
}

- (void)pushToSearchShares
{
    PresentToNibVC(@"ENSearchViewController");
//    PushToVC(@"ENSearchViewController");
}


#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _arrayShares.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ENSharesCell *cell = XIBcellFromMainBundle(@"ENSharesCell");
    
    [cell updateData:_arrayShares[indexPath.row]];
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    ENSharesTableHeaderView *thView = XIBFromMainBundle(@"ENSharesTableHeaderView");
    [thView updateData:@(_currentSortUP)];
    thView.changeShowBlock = ^(BOOL isUP) {
        [self sortShares:isUP];
        [_tableView reloadData];
    };
    return thView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 34;
}


#pragma mark - Network
//股票列表
- (void)requestSharesList
{
    _hud = [LPCMBProgressHUD showHUDAddedTo:self.view animated:YES];
    [ENInterface getSharesListWithMarket:@"sh" page:_currentPage success:^(NSDictionary *jsonDic) {
        _arrayShares = [SharesModel modelArrayFromJSONArray:jsonDic[@"showapi_res_body"][@"contentlist"]];
        if (_arrayShares.count > 0) {
            [self requestSharesDetail];
        }
    } failure:^(NSError *error) {
        [_hud hide];
    }];
}

//股票具体数据
- (void)requestSharesDetail
{
    NSMutableString *stocks = [[NSMutableString alloc] init];
//    //截取前13条数据
//    for (int i = 0; i < 13; i++) {
//        SharesModel *sharesModel = _arrayShares[i];
//        [stocks appendFormat:@"%@%@,",sharesModel.market,sharesModel.code];
//    }
    for (SharesModel *sharesModel in _arrayShares) {
        [stocks appendFormat:@"%@%@,",sharesModel.market,sharesModel.code];
    }
    if (stocks.length > 1) {
        [stocks deleteCharactersInRange:NSMakeRange(stocks.length - 1, 1)];
    }
    [ENInterface getSharesDetailListWithStocks:stocks success:^(NSDictionary *jsonDic) {
        [_hud hide];
        if ([jsonDic[@"showapi_res_body"][@"ret_code"] intValue] == -1) {
            [LPCMBProgressHUD showErrorWithText:jsonDic[@"showapi_res_body"][@"remark"]];
            return ;
        }
        //头视图数据
        NSArray *arrayIndexList = jsonDic[@"showapi_res_body"][@"indexList"];
        GCD_MAIN(^{
            [self updateHeadView:arrayIndexList];
        });
        //列表数据
        NSArray *arrayDetailList = jsonDic[@"showapi_res_body"][@"list"];
        for (int i = 0; i < _arrayShares.count; i++) {
            SharesModel *sharesModel = _arrayShares[i];
            [sharesModel setValuesForKeysWithDictionary:arrayDetailList[i]];
        }
        [self sortShares:NO];
        GCD_MAIN(^{
            [_tableView reloadData];
            [LPCMBProgressHUD showSuccessWithText:@"刷新成功"];
        });
    } failure:^(NSError *error) {
        [_hud hide];
    }];
}

@end
